'use client'

import { useState, useEffect, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import Button from '@/components/ui/Button'
import { PlusIcon, TrashIcon, UserPlusIcon, XMarkIcon } from '@heroicons/react/24/outline'
import { toast } from 'react-hot-toast'

interface Student {
  id: string
  name: string | null
  email: string
}

interface ChoiceOption {
  id: string
  text: string
}

interface MultipleChoiceContent {
  question?: string
  options: ChoiceOption[]
  correctAnswerId?: string | null
  points?: number
  answerExplanation?: string
  explanationVisibleToStudent?: boolean
}

interface FillInBlankContent {
  question?: string
  standardAnswers?: string[]
  matchCase?: boolean
  points?: number
  answerExplanation?: string
  explanationVisibleToStudent?: boolean
}

interface FileUploadContent {
  prompt?: string
  allowedFileTypes?: string
  maxFileSizeMB?: number
  points?: number
  answerExplanation?: string
  explanationVisibleToStudent?: boolean
}

interface TestCase {
  id: string; // 使用随机字符串或索引作为临时ID
  name: string;
  input: string;
  expectedOutput: string;
  points: number;
  isHidden: boolean;
}

interface CodeStageContent { 
  prompt?: string; 
  languages?: string[];
  template?: string; 
  points?: number; // 总分，可以考虑是否由测试用例累加
  answerExplanation?: string; 
  explanationVisibleToStudent?: boolean;
  testCases?: TestCase[]; // 新增测试用例
}

interface GeneralStageContent {
  points?: number
  answerExplanation?: string
  explanationVisibleToStudent?: boolean
}

interface Stage {
  id?: string
  title: string
  type: 'MULTIPLE_CHOICE' | 'FILL_IN_BLANK' | 'CODE' | 'FILE_UPLOAD'
  description: string
  content: MultipleChoiceContent | FillInBlankContent | FileUploadContent | CodeStageContent | GeneralStageContent | any
  order?: number
}

interface ExperimentAuthorization {
  student: {
    id: string
    name: string | null
    email: string
  }
}

interface ExperimentProps {
  id: string
  title: string
  description: string
  startTime: string
  endTime: string
  allowLateSubmission: boolean
  stages: Array<Omit<Stage, 'content'> & { content: string | object }>
  authorizedExperiments: ExperimentAuthorization[]
}

const generateOptionId = () => `option_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`
const generateTestCaseId = () => `testcase_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`

const calculateCodeStagePoints = (testCases: TestCase[] | undefined): number => {
  if (!testCases || testCases.length === 0) {
    return 0;
  }
  return testCases.reduce((sum, tc) => sum + (Number(tc.points) || 0), 0);
};

// Add a list of common languages for the dropdown (ensure this is defined, or import from a shared constants file)
const commonLanguages = [
  { value: 'javascript', label: 'JavaScript' },
  { value: 'python', label: 'Python' },
  { value: 'java', label: 'Java' },
  { value: 'c#', label: 'C#' },
  { value: 'cpp', label: 'C++' },
  { value: 'html', label: 'HTML' },
  { value: 'css', label: 'CSS' },
  { value: 'json', label: 'JSON' },
  { value: 'markdown', label: 'Markdown' },
  { value: 'plaintext', label: 'Plain Text' },
];

export default function ExperimentEditForm({ experiment }: { experiment: ExperimentProps }) {
  const router = useRouter()
  const [title, setTitle] = useState(experiment.title || '')
  const [description, setDescription] = useState(experiment.description || '')
  const [startTime, setStartTime] = useState('')
  const [endTime, setEndTime] = useState('')
  const [allowLateSubmission, setAllowLateSubmission] = useState(experiment.allowLateSubmission || false)
  const [stages, setStages] = useState<Stage[]>([])
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [errorMsg, setErrorMsg] = useState<string | null>(null)
  
  // 添加学生选择相关状态
  const [allStudents, setAllStudents] = useState<Student[]>([])
  const [selectedStudents, setSelectedStudents] = useState<Student[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [showStudentSearch, setShowStudentSearch] = useState(false)
  
  // 初始化表单数据
  useEffect(() => {
    if (experiment) {
      setTitle(experiment.title)
      setDescription(experiment.description || '')
      // 格式化日期时间为本地格式
      setStartTime(formatDateTimeForInput(new Date(experiment.startTime)))
      setEndTime(formatDateTimeForInput(new Date(experiment.endTime)))
      setAllowLateSubmission(experiment.allowLateSubmission)
      
      const initialStages = (experiment.stages || []).map((stage, index) => {
        let parsedContent: any = {}; // Ensure type allows for object assignment
        try {
          if (typeof stage.content === 'string' && stage.content.trim() !== '') {
            parsedContent = JSON.parse(stage.content);
          } else if (typeof stage.content === 'object' && stage.content !== null) {
            parsedContent = stage.content; 
          } else {
            // If stage.content is null, undefined, or an empty string after trim, default to empty object
            parsedContent = {}; 
          }
        } catch (e) {
          console.error("Failed to parse stage content for stage ID:", stage.id, "Content:", stage.content, "Error:", e);
          parsedContent = {}; // Default to empty if parsing fails
        }

        // Ensure content has default structure based on type if some fields are missing
        let defaultContentStructure: any = {};
        switch (stage.type) {
          case 'MULTIPLE_CHOICE':
            defaultContentStructure = {
              question: '',
              options: [{ id: generateOptionId(), text: '' }, { id: generateOptionId(), text: '' }],
              correctAnswerId: null,
              points: 10,
              answerExplanation: '',
              explanationVisibleToStudent: false,
            };
            break;
          case 'FILL_IN_BLANK':
            defaultContentStructure = {
              question: '', standardAnswers: [], matchCase: false, points: 5, answerExplanation: '', explanationVisibleToStudent: false,
            };
            break;
          case 'FILE_UPLOAD':
            defaultContentStructure = {
              prompt: '', allowedFileTypes: '.pdf,.doc,.docx,.zip,.rar,.7z,.txt', maxFileSizeMB: 10, points: 10, answerExplanation: '', explanationVisibleToStudent: false,
            };
            break;
          case 'CODE':
            let currentLanguages = parsedContent.languages;
            if (typeof parsedContent.language === 'string' && !parsedContent.languages) { 
              currentLanguages = [parsedContent.language];
            } else if (!Array.isArray(currentLanguages)) {
              currentLanguages = [commonLanguages[0].value]; 
            }
            if (currentLanguages.length === 0) currentLanguages = [commonLanguages[0].value];
            
            defaultContentStructure = {
              prompt: '', template: '// Code here', answerExplanation: '', explanationVisibleToStudent: false, 
              languages: currentLanguages,
              testCases: [], 
            };
            // Calculate points based on existing test cases if they exist in parsedContent
            // Otherwise, it will be based on defaultContentStructure (which is 0 if testCases is empty)
            // Ensure points is initialized correctly if parsedContent comes with testCases
            if (parsedContent.testCases && parsedContent.testCases.length > 0) {
                parsedContent.points = calculateCodeStagePoints(parsedContent.testCases);
            } else {
                // If no test cases in parsedContent, points should be 0 or what defaultContentStructure implies
                // If parsedContent.points was somehow set but testCases is empty, recalculate to 0
                if (!parsedContent.testCases || parsedContent.testCases.length === 0) {
                    parsedContent.points = 0;
                }
            }
            if (!parsedContent.testCases) parsedContent.testCases = []; // Ensure testCases array exists
            
            break;
          default:
            defaultContentStructure = {
              points: 10, answerExplanation: '', explanationVisibleToStudent: false,
            };
            break;
        }

        return {
        id: stage.id,
        title: stage.title,
        type: stage.type as Stage['type'],
        description: stage.description || '',
          content: { ...defaultContentStructure, ...parsedContent },
          order: stage.order !== undefined ? stage.order : index + 1
        };
      });
      setStages(initialStages.sort((a, b) => (a.order || 0) - (b.order || 0)));
      
      // 处理已授权学生
      if (experiment.authorizedExperiments && experiment.authorizedExperiments.length > 0) {
        const initialSelectedStudents = experiment.authorizedExperiments.map(auth => ({
          id: auth.student.id,
          name: auth.student.name || '',
          email: auth.student.email
        }))
        setSelectedStudents(initialSelectedStudents)
      } else {
        setSelectedStudents([])
      }
    }
  }, [experiment])
  
  // 格式化日期时间为input所需格式
  const formatDateTimeForInput = (date: Date) => {
    if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
        // Handle invalid date, perhaps return empty string or a default
        return ''; 
    }
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day}T${hours}:${minutes}`
  }
  
  // 获取所有学生
  useEffect(() => {
    const fetchStudents = async () => {
      try {
        const response = await fetch('/api/users?role=STUDENT')
        if (response.ok) {
          const data = await response.json()
          setAllStudents(data)
        } else {
          console.error('获取学生列表失败')
        }
      } catch (error) {
        console.error('获取学生列表错误:', error)
      }
    }
    
    fetchStudents()
  }, [])

  const handleAddStage = () => {
    setStages(prevStages => [
      ...prevStages,
      {
        // id will be undefined for new stages, backend will generate it
        title: '',
        type: 'MULTIPLE_CHOICE',
        description: '',
        content: {
          question: '', options: [{ id: generateOptionId(), text: '' }, { id: generateOptionId(), text: '' }], correctAnswerId: null, points: 10, answerExplanation: '', explanationVisibleToStudent: false,
        } as MultipleChoiceContent,
        order: prevStages.length + 1
      },
    ])
  }

  const handleRemoveStage = (index: number) => {
    // Consider how to handle deleting existing stages (marked for deletion vs. immediate removal from state)
    setStages(stages.filter((_, i) => i !== index))
  }

  const handleStageChange = (
    stageIndex: number, 
    field: keyof Stage | `content.${string}`,
    value: any,
    optionValue?: string,
    testCaseIndex?: number, // 用于测试用例内部字段的更新
    testCaseField?: keyof TestCase // 用于测试用例内部字段的更新
  ) => {
    setStages(prevStages =>
      prevStages.map((stage, i) => {
        if (i === stageIndex) {
          const updatedStage = { ...stage }
          if (typeof field === 'string' && field.startsWith('content.')) {
            const contentField = field.substring(8)
            let newContent = { ...stage.content } 

            if (stage.type === 'MULTIPLE_CHOICE') {
              newContent = { ...(stage.content as MultipleChoiceContent) }
              if (contentField.startsWith('options.')) {
                const optionPath = contentField.substring(8).split('.')
                const optionIndex = parseInt(optionPath[0])
                const optionProperty = optionPath[1] as keyof ChoiceOption
                if (newContent.options && newContent.options[optionIndex]) {
                  const updatedOptions = [...newContent.options]
                  updatedOptions[optionIndex] = { ...updatedOptions[optionIndex], [optionProperty]: value }
                  newContent.options = updatedOptions
                }
              } else if (contentField === 'correctAnswerId') {
                (newContent as MultipleChoiceContent).correctAnswerId = value
              } else if (contentField === 'points') {
                (newContent as MultipleChoiceContent).points = Number(value) >= 0 ? Number(value) : 0
              } else if (contentField === 'answerExplanation'){
                (newContent as MultipleChoiceContent).answerExplanation = value
              } else if (contentField === 'explanationVisibleToStudent'){
                (newContent as MultipleChoiceContent).explanationVisibleToStudent = Boolean(value)
              } else {
                (newContent as any)[contentField] = value
              }
            } else if (stage.type === 'FILL_IN_BLANK') {
              newContent = { ...(stage.content as FillInBlankContent) }
              if (contentField === 'standardAnswers') {
                (newContent as FillInBlankContent).standardAnswers = typeof value === 'string' ? value.split(',').map(s => s.trim()).filter(s => s) : []
              } else if (contentField === 'matchCase') {
                (newContent as FillInBlankContent).matchCase = Boolean(value)
              } else if (contentField === 'points') {
                (newContent as FillInBlankContent).points = Number(value) >= 0 ? Number(value) : 0
              } else if (contentField === 'answerExplanation'){
                (newContent as FillInBlankContent).answerExplanation = value
              } else if (contentField === 'explanationVisibleToStudent'){
                (newContent as FillInBlankContent).explanationVisibleToStudent = Boolean(value)
              } else {
                (newContent as any)[contentField] = value
              }
            } else if (stage.type === 'FILE_UPLOAD') {
              newContent = { ...(stage.content as FileUploadContent) }
              if (contentField === 'prompt') {
                (newContent as FileUploadContent).prompt = value
              } else if (contentField === 'allowedFileTypes') {
                (newContent as FileUploadContent).allowedFileTypes = value
              } else if (contentField === 'maxFileSizeMB') {
                (newContent as FileUploadContent).maxFileSizeMB = Number(value) > 0 ? Number(value) : undefined
              } else if (contentField === 'points') {
                (newContent as FileUploadContent).points = Number(value) >= 0 ? Number(value) : 0
              } else if (contentField === 'answerExplanation'){
                (newContent as FileUploadContent).answerExplanation = value
              } else if (contentField === 'explanationVisibleToStudent'){
                (newContent as FileUploadContent).explanationVisibleToStudent = Boolean(value)
              } else {
                (newContent as any)[contentField] = value
              }
            } else if (stage.type === 'CODE') {
              newContent = { ...(stage.content as CodeStageContent) }
              if (contentField === 'languages') {
                const currentLanguages = Array.isArray((newContent as CodeStageContent).languages) ? (newContent as CodeStageContent).languages : [];
                let updatedLanguages;
                if (value === true && optionValue) { 
                  updatedLanguages = (currentLanguages || []).includes(optionValue) ? (currentLanguages || []) : [...(currentLanguages || []), optionValue];
                } else if (value === false && optionValue) {
                  updatedLanguages = (currentLanguages || []).filter(lang => lang !== optionValue);
                } else if (Array.isArray(value)) { // 允许直接设置整个语言数组
                  updatedLanguages = value;
                } else { 
                  updatedLanguages = currentLanguages; 
                }
                (newContent as CodeStageContent).languages = updatedLanguages;
              } else if (contentField === 'testCases' && typeof testCaseIndex === 'number' && testCaseField) {
                const currentTestCases = (newContent as CodeStageContent).testCases || [];
                const updatedTestCases = [...currentTestCases];
                if (updatedTestCases[testCaseIndex]) {
                  updatedTestCases[testCaseIndex] = {
                    ...updatedTestCases[testCaseIndex],
                    [testCaseField]: testCaseField === 'points' ? (Number(value) || 0) : value
                  };
                  (newContent as CodeStageContent).testCases = updatedTestCases;
                  // If the points of a test case changed, or any other field that might imply a re-render for points,
                  // recalculate total points for the stage.
                  (newContent as CodeStageContent).points = calculateCodeStagePoints(updatedTestCases);
                }
              } else if (contentField !== 'points') { // Prevent direct edit of 'points' via general content field update
                (newContent as any)[contentField] = value
              }
            } else {
              (newContent as any)[contentField] = value
            }

            // Uniformly handle points, answerExplanation, explanationVisibleToStudent if they are part of contentField
            if (contentField === 'points') newContent.points = Number(value) >= 0 ? Number(value) : 0;
            if (contentField === 'answerExplanation') newContent.answerExplanation = value;
            if (contentField === 'explanationVisibleToStudent') newContent.explanationVisibleToStudent = Boolean(value);

            updatedStage.content = newContent
          } else {
            (updatedStage as any)[field as keyof Stage] = value
            if (field === 'type') { // When type changes, re-initialize content with defaults for that type
              let defaultContent:any = { points: 10, answerExplanation: '', explanationVisibleToStudent: false };
              switch(value as Stage['type']) {
                case 'MULTIPLE_CHOICE': defaultContent = { ...defaultContent, question: '', options: [{ id: generateOptionId(), text: '' }, { id: generateOptionId(), text: '' }], correctAnswerId: null}; break;
                case 'FILL_IN_BLANK': defaultContent = { ...defaultContent, question: '', standardAnswers: [], matchCase: false, points: 5}; break;
                case 'FILE_UPLOAD': defaultContent = { ...defaultContent, prompt: '', allowedFileTypes: '.pdf,.doc,.docx,.zip,.rar,.7z,.txt', maxFileSizeMB: 10 }; break;
                case 'CODE': defaultContent = { ...defaultContent, prompt: '', languages: [commonLanguages[0].value], template: '// Code here', points: 0, testCases: [] }; break; // Points start at 0
              }
              updatedStage.content = defaultContent;
            }
          }
          return updatedStage
        }
        return stage
      })
    )
  }

  const handleAddOption = (stageIndex: number) => {
    setStages(prevStages => 
      prevStages.map((stage, i) => {
        if (i === stageIndex && stage.type === 'MULTIPLE_CHOICE') {
          const content = stage.content as MultipleChoiceContent
          return {
            ...stage,
            content: {
              ...content,
              options: [...(content.options || []), { id: generateOptionId(), text: '' }],
            },
          }
        }
        return stage
      })
    )
  }

  const handleRemoveOption = (stageIndex: number, optionIndex: number) => {
    setStages(prevStages =>
      prevStages.map((stage, i) => {
        if (i === stageIndex && stage.type === 'MULTIPLE_CHOICE') {
          const content = stage.content as MultipleChoiceContent
          let newCorrectAnswerId = content.correctAnswerId
          if (content.options[optionIndex]?.id === newCorrectAnswerId) {
            newCorrectAnswerId = null
          }
          return {
            ...stage,
            content: {
              ...content,
              options: content.options.filter((_, idx) => idx !== optionIndex),
              correctAnswerId: newCorrectAnswerId,
            },
          }
        }
        return stage
      })
    )
  }
  
  const handleSetCorrectAnswer = (stageIndex: number, optionId: string) => {
    handleStageChange(stageIndex, 'content.correctAnswerId', optionId)
  }
  
  // 测试用例相关函数
  const handleAddTestCase = (stageIndex: number) => {
    setStages(prevStages => 
      prevStages.map((stage, i) => {
        if (i === stageIndex && stage.type === 'CODE') {
          const content = stage.content as CodeStageContent;
          const newTestCase: TestCase = {
            id: generateTestCaseId(),
            name: `测试 ${ (content.testCases?.length || 0) + 1}`,
            input: '',
            expectedOutput: '',
            points: 0, // Default new test case points to 0
            isHidden: false,
          };
          const newTestCases = [...(content.testCases || []), newTestCase];
          const newTotalPoints = calculateCodeStagePoints(newTestCases);
          return {
            ...stage,
            content: {
              ...content,
              testCases: newTestCases,
              points: newTotalPoints, // Update total points
            },
          };
        }
        return stage;
      })
    );
  };

  const handleRemoveTestCase = (stageIndex: number, testCaseIdToRemove: string) => {
    setStages(prevStages =>
      prevStages.map((stage, i) => {
        if (i === stageIndex && stage.type === 'CODE') {
          const content = stage.content as CodeStageContent;
          const newTestCases = (content.testCases || []).filter(tc => tc.id !== testCaseIdToRemove);
          const newTotalPoints = calculateCodeStagePoints(newTestCases);
          return {
            ...stage,
            content: {
              ...content,
              testCases: newTestCases,
              points: newTotalPoints, // Update total points
            },
          };
        }
        return stage;
      })
    );
  };
  
  // 学生选择相关函数
  const handleAddStudent = (student: Student) => {
    if (!selectedStudents.some(s => s.id === student.id)) {
      setSelectedStudents([...selectedStudents, student])
    }
    setSearchTerm('')
  }
  
  const handleRemoveStudent = (studentId: string) => {
    setSelectedStudents(selectedStudents.filter(s => s.id !== studentId))
  }
  
  const filteredStudents = allStudents.filter(student => 
    !selectedStudents.some(s => s.id === student.id) && 
    (student.name?.toLowerCase().includes(searchTerm.toLowerCase()) || 
     student.email.toLowerCase().includes(searchTerm.toLowerCase()))
  )

  const deleteExperiment = async () => {
    // 重置错误信息
    if (!confirm('确定要删除这个实验吗？')) {
      return
    }

    try{
      const response = await fetch(`/api/experiments/${experiment.id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(null),
      })

      console.log('API响应状态:', response.status, response.statusText)

      const responseData = await response.json()
      console.log('API响应数据:', responseData)

      if (!response.ok) {
        const errorMessage = responseData.error || responseData.message || '删除实验失败';
        console.error('删除失败详情:', responseData);
        setErrorMsg(errorMessage);
        throw new Error(errorMessage);
      }

      toast.success('实验删除成功')
      router.push(`/experiments`)
      router.refresh()
    } catch (error) {
      console.error('删除实验失败:', error)
      const errorMessage = error instanceof Error ? error.message : '删除实验失败，请重试'
      setErrorMsg(errorMessage)
      toast.error(errorMessage)
    } finally {
      setIsSubmitting(false)
    }
  }

  const validateStages = (stages: Stage[]) => {
    for (const stage of stages) {
      if (!stage.title.trim()) {
        toast.error('请填写所有实验阶段的标题')
        return false
      }
      if (!stage.type) {
        toast.error('请选择所有实验阶段的类型')
        return false
      }
    }
    return true
  }

  const validateForm = () => {
    if (!title.trim()) {
      toast.error('请输入实验标题')
      return false
    }
    if (!startTime) {
      toast.error('请选择开始时间')
      return false
    }
    if (!endTime) {
      toast.error('请选择结束时间')
      return false
    }
    if (new Date(startTime) >= new Date(endTime)) {
      toast.error('结束时间必须晚于开始时间')
      return false
    }
    if (stages.length === 0) {
      toast.error('请至少添加一个实验阶段')
      return false
    }
    
    return validateStages(stages)
  }

  const processStageDataForSubmit = (stage: Stage) => {
    return {
      id: stage.id, // Include id for existing stages to be updated
      title: stage.title.trim(),
      description: (stage.description || '').trim(),
      type: stage.type,
      order: stage.order, // Ensure order is preserved or recalculated if stages can be reordered
      content: JSON.stringify(stage.content || {}), // Stringify the rich content object
    };
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) return;
    setIsSubmitting(true);
    setErrorMsg(null);
    
    try {
      const processedStages = stages.map((stage, index) => 
        processStageDataForSubmit({ ...stage, order: index + 1 })
      );
      
      const experimentData = {
        title: title.trim(),
        description: description.trim(),
        startTime,
        endTime,
        allowLateSubmission,
        stages: processedStages,
        authorizedExperiments: selectedStudents.map(student => student.id),
      };
      
      const response = await fetch(`/api/experiments/${experiment.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(experimentData),
      });
      
      const responseData = await response.json();
      if (!response.ok) {
        throw new Error(responseData.message || '更新实验失败');
      }
      toast.success('实验更新成功!');
      router.push(`/experiments/${experiment.id}`);
      router.refresh(); 
      } catch (err: any) {
      console.error('更新实验错误:', err);
      setErrorMsg(err.message || '更新实验失败，请重试');
      toast.error(err.message || '更新实验失败');
      } finally {
      setIsSubmitting(false);
    }
  };
  
  const [loading, setLoading] = useState(false); 
  const [error, setError] = useState(''); 

  return (
    <form onSubmit={handleSubmit} className="space-y-8">
      {errorMsg && (
        <div className="bg-red-50 border border-red-300 text-red-700 px-4 py-3 rounded">
          <p className="font-medium">更新失败</p>
          <p className="text-sm">{errorMsg}</p>
        </div>
      )}
      
      <div className="space-y-6 bg-white p-6 rounded-lg shadow">
        <div>
          <label htmlFor="title" className="block text-sm font-medium text-gray-700">
            实验标题
          </label>
          <input
            type="text"
            name="title"
            id="title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
            required
          />
        </div>

        <div>
          <label htmlFor="description" className="block text-sm font-medium text-gray-700">
            实验描述
          </label>
          <textarea
            id="description"
            name="description"
            rows={3}
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
          />
        </div>

        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
          <div>
            <label htmlFor="startTime" className="block text-sm font-medium text-gray-700">
              开始时间
            </label>
            <input
              type="datetime-local"
              name="startTime"
              id="startTime"
              value={startTime}
              onChange={(e) => setStartTime(e.target.value)}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
              required
            />
          </div>

          <div>
            <label htmlFor="endTime" className="block text-sm font-medium text-gray-700">
              结束时间
            </label>
            <input
              type="datetime-local"
              name="endTime"
              id="endTime"
              value={endTime}
              onChange={(e) => setEndTime(e.target.value)}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
              required
            />
          </div>
        </div>

        <div className="flex items-center">
          <input
            id="allowLateSubmission"
            name="allowLateSubmission"
            type="checkbox"
            checked={allowLateSubmission}
            onChange={(e) => setAllowLateSubmission(e.target.checked)}
            className="h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
          />
          <label htmlFor="allowLateSubmission" className="ml-2 block text-sm text-gray-900">
            允许截止后提交
          </label>
        </div>
      </div>
      
      <div className="space-y-6 bg-white p-6 rounded-lg shadow">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-medium text-gray-900">授权学生</h3>
          <Button
            type="button"
            variant="outline"
            onClick={() => setShowStudentSearch(!showStudentSearch)}
            className="inline-flex items-center"
          >
            <UserPlusIcon className="h-5 w-5 mr-1" />
            {showStudentSearch ? '取消添加' : '添加学生'}
          </Button>
        </div>
        
        {showStudentSearch && (
          <div className="mt-4">
            <label htmlFor="studentSearch" className="block text-sm font-medium text-gray-700">
              搜索学生
            </label>
            <div className="mt-1 relative">
              <input
                type="text"
                id="studentSearch"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="输入姓名或邮箱搜索"
                className="shadow-sm focus:ring-primary-500 focus:border-primary-500 block w-full sm:text-sm border-gray-300 rounded-md"
              />
              {searchTerm && filteredStudents.length > 0 && (
                <div className="absolute z-10 mt-1 w-full bg-white shadow-lg max-h-60 rounded-md overflow-auto">
                  <ul className="divide-y divide-gray-200">
                    {filteredStudents.map(student => (
                      <li 
                        key={student.id} 
                        className="px-4 py-2 hover:bg-gray-100 cursor-pointer"
                        onClick={() => handleAddStudent(student)}
                      >
                        <div className="flex items-center">
                          <div>
                            <p className="text-sm font-medium text-gray-900">{student.name}</p>
                            <p className="text-sm text-gray-500">{student.email}</p>
                          </div>
                        </div>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          </div>
        )}
        
        <div className="mt-4">
          {selectedStudents.length === 0 ? (
            <p className="text-sm text-gray-500">未选择学生，所有学生都无法访问该实验除非特别授权</p>
          ) : (
            <div className="flex flex-wrap gap-2">
              {selectedStudents.map(student => (
                <div
                  key={student.id}
                  className="inline-flex items-center bg-gray-100 rounded-full px-3 py-1 text-sm"
                >
                  <span className="truncate">{student.name || student.email}</span>
                  <button
                    type="button"
                    onClick={() => handleRemoveStudent(student.id)}
                    className="ml-1 text-gray-500 hover:text-gray-700"
                  >
                    <XMarkIcon className="h-4 w-4" />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="space-y-6 bg-white p-6 rounded-lg shadow">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-medium text-gray-900">实验阶段</h3>
          <Button
            type="button"
            variant="outline"
            onClick={handleAddStage}
            className="inline-flex items-center"
          >
            <PlusIcon className="h-5 w-5 mr-1" />
            添加阶段
          </Button>
        </div>

        <div className="space-y-6">
          {stages.map((stage, stageIndex) => (
            <div key={stage.id || stageIndex} className="border rounded-lg p-4 relative space-y-4">
              <button
                type="button"
                onClick={() => handleRemoveStage(stageIndex)}
                className="absolute top-3 right-3 text-gray-400 hover:text-gray-600 p-1"
              >
                <TrashIcon className="h-5 w-5" />
              </button>

              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    阶段标题
                  </label>
                  <input
                    type="text"
                    value={stage.title}
                    onChange={(e) => handleStageChange(stageIndex, 'title', e.target.value)}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700">
                    阶段类型
                  </label>
                  <select
                    value={stage.type}
                    onChange={(e) => { const newType = e.target.value as Stage['type']; handleStageChange(stageIndex, 'type', newType);}}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                  >
                    <option value="MULTIPLE_CHOICE">选择题</option>
                    <option value="FILL_IN_BLANK">填空题</option>
                    <option value="CODE">代码题</option>
                    <option value="FILE_UPLOAD">文件上传</option>
                  </select>
                </div>
                </div>

              <div>
                  <label className="block text-sm font-medium text-gray-700">
                    阶段描述
                  </label>
                  <textarea
                    value={stage.description}
                  onChange={(e) => handleStageChange(stageIndex, 'description', e.target.value)}
                    rows={2}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                  />
                </div>

              {stage.type === 'MULTIPLE_CHOICE' && (
                <div className="border-t border-gray-200 pt-4 mt-4 space-y-4">
                  <h4 className="text-md font-medium text-gray-800">选择题内容:</h4>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-mc-question`} className="block text-sm font-medium text-gray-700">题目 <span className="text-red-500">*</span></label>
                    <textarea
                      id={`stage-${stageIndex}-mc-question`}
                      value={(stage.content as MultipleChoiceContent)?.question || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.question', e.target.value)}
                      rows={3}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      placeholder="输入选择题的题干"
                      required
                    />
              </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700">选项 <span className="text-red-500">*</span> (至少2个)</label>
                    <div className="mt-2 space-y-3">
                      {((stage.content as MultipleChoiceContent)?.options || []).map((option) => (
                        <label key={option.id} className="flex items-center p-3 border rounded-md hover:bg-gray-50 cursor-pointer">
                          <input
                            type="radio"
                            checked={(stage.content as MultipleChoiceContent)?.correctAnswerId === option.id}
                            onChange={() => handleStageChange(stageIndex, 'content.correctAnswerId', option.id)}
                            className="h-4 w-4 text-primary-600 border-gray-300 focus:ring-primary-500"
                          />
                          <span className="ml-3 text-gray-800">{option.text}</span>
                        </label>
                      ))}
                    </div>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => handleAddOption(stageIndex)}
                      className="mt-2 text-primary-600 hover:text-primary-800"
                    >
                      <PlusIcon className="h-4 w-4 mr-1" /> 添加选项
                    </Button>
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-mc-points`} className="block text-sm font-medium text-gray-700">分值</label>
                    <input
                      type="number"
                      id={`stage-${stageIndex}-mc-points`}
                      value={(stage.content as MultipleChoiceContent)?.points || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.points', parseInt(e.target.value, 10))}
                      className="mt-1 block w-1/4 rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      min="0"
                      placeholder="例如: 10"
                    />
                  </div>
                </div>
              )}
              {stage.type === 'FILL_IN_BLANK' && (
                <div className="border-t border-gray-200 pt-4 mt-4 space-y-4">
                  <h4 className="text-md font-medium text-gray-800">填空题内容:</h4>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fib-question`} className="block text-sm font-medium text-gray-700">题干/说明 (用 "__" 表示填空处，可选)</label>
                    <textarea
                      id={`stage-${stageIndex}-fib-question`}
                      value={(stage.content as FillInBlankContent)?.question || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.question', e.target.value)}
                      rows={3}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      placeholder="例如：地球的唯一天然卫星是 __ 。"
                    />
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fib-answers`} className="block text-sm font-medium text-gray-700">标准答案 (多个答案请用英文逗号 "," 分隔) <span className="text-red-500">*</span></label>
                    <input
                      type="text"
                      id={`stage-${stageIndex}-fib-answers`}
                      value={((stage.content as FillInBlankContent)?.standardAnswers || []).join(',')}
                      onChange={(e) => handleStageChange(stageIndex, 'content.standardAnswers', e.target.value)}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      placeholder="例如：月球,月亮"
                      required
                    />
                  </div>
                  <div className="flex items-center">
                    <input
                      type="checkbox"
                      id={`stage-${stageIndex}-fib-matchcase`}
                      checked={(stage.content as FillInBlankContent)?.matchCase || false}
                      onChange={(e) => handleStageChange(stageIndex, 'content.matchCase', e.target.checked)}
                      className="h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                    />
                    <label htmlFor={`stage-${stageIndex}-fib-matchcase`} className="ml-2 block text-sm text-gray-900">匹配时区分大小写</label>
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fib-points`} className="block text-sm font-medium text-gray-700">分值</label>
                    <input
                      type="number"
                      id={`stage-${stageIndex}-fib-points`}
                      value={(stage.content as FillInBlankContent)?.points || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.points', parseInt(e.target.value, 10))}
                      className="mt-1 block w-1/4 rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      min="0"
                      placeholder="例如: 5"
                    />
                  </div>
                </div>
              )}
              {stage.type === 'FILE_UPLOAD' && (
                <div className="border-t border-gray-200 pt-4 mt-4 space-y-4">
                  <h4 className="text-md font-medium text-gray-800">文件上传题设置:</h4>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fu-prompt`} className="block text-sm font-medium text-gray-700">题干 / 提交说明与要求 <span className="text-red-500">*</span></label>
                    <textarea
                      id={`stage-${stageIndex}-fu-prompt`}
                      value={(stage.content as FileUploadContent)?.prompt || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.prompt', e.target.value)}
                      rows={3}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      placeholder="例如：请上传您的实验报告..."
                      required
                    />
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fu-filetypes`} className="block text-sm font-medium text-gray-700">允许的文件类型 (英文逗号分隔)</label>
                    <input
                      type="text"
                      id={`stage-${stageIndex}-fu-filetypes`}
                      value={(stage.content as FileUploadContent)?.allowedFileTypes || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.allowedFileTypes', e.target.value)}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      placeholder=".pdf,.zip"
                    />
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fu-maxsize`} className="block text-sm font-medium text-gray-700">最大文件大小 (MB)</label>
                    <input
                      type="number"
                      id={`stage-${stageIndex}-fu-maxsize`}
                      value={(stage.content as FileUploadContent)?.maxFileSizeMB || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.maxFileSizeMB', e.target.value ? parseInt(e.target.value, 10) : undefined)}
                      className="mt-1 block w-1/4 rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      min="1"
                      placeholder="10"
                    />
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-fu-points`} className="block text-sm font-medium text-gray-700">分值</label>
                    <input
                      type="number"
                      id={`stage-${stageIndex}-fu-points`}
                      value={(stage.content as FileUploadContent)?.points || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.points', parseInt(e.target.value, 10))}
                      className="mt-1 block w-1/4 rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      min="0"
                      placeholder="20"
                    />
                  </div>
                </div>
              )}
              {stage.type === 'CODE' && (
                <div className="border-t border-gray-200 pt-4 mt-4 space-y-4">
                  <h4 className="text-md font-medium text-gray-800">代码题设置:</h4>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-code-prompt`} className="block text-sm font-medium text-gray-700">题干 / 编程要求 <span className="text-red-500">*</span></label>
                    <textarea
                      id={`stage-${stageIndex}-code-prompt`}
                      value={(stage.content as CodeStageContent)?.prompt || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.prompt', e.target.value)}
                      rows={4}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      placeholder="详细描述编程任务、输入输出格式、约束条件等。"
                      required
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700">允许的编程语言 (可多选)</label>
                    <div className="mt-2 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2">
                      {commonLanguages.map(lang => (
                        <div key={lang.value} className="flex items-center">
                          <input
                            type="checkbox"
                            id={`stage-${stageIndex}-code-lang-${lang.value}`}
                            checked={((stage.content as CodeStageContent)?.languages || []).includes(lang.value)}
                            onChange={(e) => handleStageChange(stageIndex, 'content.languages', e.target.checked, lang.value)}
                            className="h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                          />
                          <label htmlFor={`stage-${stageIndex}-code-lang-${lang.value}`} className="ml-2 text-sm text-gray-700">{lang.label}</label>
                        </div>
                      ))}
                    </div>
                     {/* 显示错误提示，如果语言选择为空 */}
                     {!((stage.content as CodeStageContent)?.languages || []).length && (
                        <p className="text-xs text-red-500 mt-1">请至少选择一种编程语言。</p>
                    )}
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-code-template`} className="block text-sm font-medium text-gray-700">代码模板 (可选)</label>
                    <textarea
                      id={`stage-${stageIndex}-code-template`}
                      value={(stage.content as CodeStageContent)?.template || ''}
                      onChange={(e) => handleStageChange(stageIndex, 'content.template', e.target.value)}
                      rows={6}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm font-mono"
                      placeholder="// 在此编写您的代码模板&#10;// 例如：&#10;function main() {&#10;  // 请在此处实现功能&#10;}"
                    />
                  </div>
                  <div>
                    <label htmlFor={`stage-${stageIndex}-code-points`} className="block text-sm font-medium text-gray-700">分值 (自动计算)</label>
                    <input
                      type="number"
                      id={`stage-${stageIndex}-code-points`}
                      value={(stage.content as CodeStageContent)?.points || 0}
                      readOnly // Make this read-only
                      className="mt-1 block w-1/4 rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm bg-gray-100" // Style as read-only
                      placeholder="0"
                    />
                  </div>
                </div>
              )}
              <div className="border-t border-gray-200 pt-4 mt-6">
                <div className="flex justify-between items-center mb-3">
                  <h5 className="text-md font-medium text-gray-800">测试用例:</h5>
                  <Button 
                    type="button" 
                    variant="outline"
                    size="sm"
                    onClick={() => handleAddTestCase(stageIndex)}
                  >
                    <PlusIcon className="h-4 w-4 mr-1" /> 添加测试用例
                  </Button>
                </div>
                
                {(stage.content as CodeStageContent).testCases && (stage.content as CodeStageContent).testCases!.length > 0 ? (
                  <div className="space-y-4">
                    {(stage.content as CodeStageContent).testCases!.map((testCase, tcIndex) => (
                      <div key={testCase.id} className="border rounded-md p-3 bg-gray-50 space-y-3">
                        <div className="flex justify-between items-center">
                          <input 
                            type="text"
                            value={testCase.name}
                            placeholder={`测试用例 ${tcIndex + 1} 名称`}
                            onChange={(e) => handleStageChange(stageIndex, 'content.testCases', e.target.value, undefined, tcIndex, 'name')}
                            className="text-sm font-medium p-1 border-b border-gray-300 focus:border-primary-500 outline-none flex-grow"
                          />
                          <button
                            type="button"
                            onClick={() => handleRemoveTestCase(stageIndex, testCase.id)}
                            className="text-red-500 hover:text-red-700 p-1 ml-2"
                            title="删除此测试用例"
                          >
                            <TrashIcon className="h-4 w-4" />
                          </button>
                        </div>

                        <div>
                          <label htmlFor={`stage-${stageIndex}-tc-${tcIndex}-input`} className="block text-xs font-medium text-gray-600">输入 (Input):</label>
                          <textarea 
                            id={`stage-${stageIndex}-tc-${tcIndex}-input`}
                            value={testCase.input}
                            onChange={(e) => handleStageChange(stageIndex, 'content.testCases', e.target.value, undefined, tcIndex, 'input')}
                            rows={2}
                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm font-mono text-xs"
                            placeholder="测试用例的输入数据..."
                          />
                        </div>
                        <div>
                          <label htmlFor={`stage-${stageIndex}-tc-${tcIndex}-output`} className="block text-xs font-medium text-gray-600">预期输出 (Expected Output):</label>
                          <textarea 
                            id={`stage-${stageIndex}-tc-${tcIndex}-output`}
                            value={testCase.expectedOutput}
                            onChange={(e) => handleStageChange(stageIndex, 'content.testCases', e.target.value, undefined, tcIndex, 'expectedOutput')}
                            rows={2}
                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm font-mono text-xs"
                            placeholder="期望的输出结果..."
                          />
                        </div>
                        <div className="grid grid-cols-2 gap-3">
                            <div>
                                <label htmlFor={`stage-${stageIndex}-tc-${tcIndex}-points`} className="block text-xs font-medium text-gray-600">分值:</label>
                                <input 
                                    type="number"
                                    id={`stage-${stageIndex}-tc-${tcIndex}-points`}
                                    value={testCase.points}
                                    onChange={(e) => handleStageChange(stageIndex, 'content.testCases', parseInt(e.target.value, 10) || 0, undefined, tcIndex, 'points')}
                                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                                    min="0"
                                />
                            </div>
                            <div className="flex items-end pb-1">
                                <input 
                                    type="checkbox"
                                    id={`stage-${stageIndex}-tc-${tcIndex}-hidden`}
                                    checked={testCase.isHidden}
                                    onChange={(e) => handleStageChange(stageIndex, 'content.testCases', e.target.checked, undefined, tcIndex, 'isHidden')}
                                    className="h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                                />
                                <label htmlFor={`stage-${stageIndex}-tc-${tcIndex}-hidden`} className="ml-2 text-xs font-medium text-gray-600">对学生隐藏输入/输出</label>
                            </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <p className="text-xs text-gray-500 text-center py-2">暂无测试用例，点击上方按钮添加。</p>
                )}
              </div>
              <div className="border-t border-gray-200 pt-4 mt-4 space-y-4">
                <div>
                  <label htmlFor={`stage-${stageIndex}-explanation`} className="block text-sm font-medium text-gray-700">答案解析/说明</label>
                  <textarea
                    id={`stage-${stageIndex}-explanation`}
                    value={(stage.content as GeneralStageContent)?.answerExplanation || ''}
                    onChange={(e) => handleStageChange(stageIndex, 'content.answerExplanation', e.target.value)}
                    rows={4}
                    className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                    placeholder="输入该阶段的答案解析、评分标准或参考思路。"
                  />
                </div>
                <div className="flex items-center">
                  <input
                    type="checkbox"
                    id={`stage-${stageIndex}-explanation-visible`}
                    checked={(stage.content as GeneralStageContent)?.explanationVisibleToStudent || false}
                    onChange={(e) => handleStageChange(stageIndex, 'content.explanationVisibleToStudent', e.target.checked)}
                    className="h-4 w-4 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
                  />
                  <label htmlFor={`stage-${stageIndex}-explanation-visible`} className="ml-2 block text-sm text-gray-900">提交后对学生可见此解析</label>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="flex justify-end space-x-4">
        <Button
          type="button"
          variant="outline"
          onClick={() => router.back()}
          disabled={isSubmitting}
        >
          取消
        </Button>
        <Button type="submit" disabled={isSubmitting}>
          {isSubmitting ? '保存中...' : '保存更改'}
        </Button>
        <Button
            type="button"
            className="text-red-600 hover:text-red-700 border-red-300 hover:border-red-500 hover:bg-red-50"
            onClick={deleteExperiment}
            disabled={isSubmitting}
        >
          删除实验
        </Button>
      </div>
    </form>
  )
} 